package com.y.fund.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.y.fund.aacore.dao.BaseDAO;
import com.y.fund.aacore.data.DataVo;
import com.y.fund.config.ResoConfig;
import com.y.fund.utils.FileUtil;
import com.y.fund.utils.IdGenerator;
import com.y.fund.utils.StrUtil;
import com.y.fund.web.aavo.com.UploadVo;


@Service("uploadService")
public class UploadService {

	@Autowired
	ResoConfig resoConfig;
	
	@Autowired
	BaseDAO baseDao;


	/** 
	 return：
	{
	    "err_code": 10000,
	    "err_msg": null,
	    "id": "20200825110932280711000448909884",
	    "path": "/2020/08/25/20200825110932280711000448909884.json",
	    "originalName": ".postman_collection.json"
	}
	 */
	public DataVo upload2Disk$Flag(MultipartFile file, String bizFlag, boolean logInfo) {
		return upload2Disk(file, bizFlag, null, null, null, logInfo);
	}
	
	/** 
	 return：
	{
	    "err_code": 10000,
	    "err_msg": null,
	    "id": "20200825110932280711000448909884",
	    "path": "/2020/08/25/20200825110932280711000448909884.json",
	    "originalName": ".postman_collection.json"
	}
	 */
	public DataVo upload2Disk(MultipartFile file, String bizFlag, String relativeDir, String writeFileName, boolean logInfo) {
		return upload2Disk(file, bizFlag, relativeDir, writeFileName, null, logInfo);
	}
	
	/** 
	 return：
	{
	    "err_code": 10000,
	    "err_msg": null,
	    "id": "20200825110932280711000448909884",
	    "path": "/2020/08/25/20200825110932280711000448909884.json",
	    "originalName": ".postman_collection.json"
	}
	 */
	public DataVo upload2Disk(MultipartFile file, String bizFlag, String relativeDir, String writeFileName, String bizId, boolean logInfo) {
		if(null == file) {
			return DataVo.Fail("File is Null");
		}
		String originalName = file.getOriginalFilename();
		originalName = StrUtil.replaceAll(originalName, "\\", "/");
		if(originalName.indexOf("/")!=-1){
			originalName = originalName.substring(originalName.lastIndexOf("/"));
		}
		if(StrUtil.isBlankIncNullStr(originalName)) {
			return DataVo.Fail("File Name is error ");
		}
		String ext = FileUtil.GetSuffix(originalName);
   		if(FileUtil.dangerSuffixs.contains(ext)){
			return DataVo.Fail("Danger File Type.");
		}
   		
   		if(StrUtil.isBlankIncNullStr(relativeDir)) {
   			relativeDir = FileUtil.NewRelativeDir();
   		}

   		if(StrUtil.isBlankIncNullStr(writeFileName)) {
   			writeFileName = IdGenerator.Id26WithoutYearMonthDay().concat(ext);
   		}

   		final String relPath = relativeDir.concat("/").concat(writeFileName);
   		
		String fullUploadDir = FileUtil.ConcatPath(resoConfig.getDiskUpload(), relativeDir);
		File d = new File(fullUploadDir);
		if(!d.exists()){
			try{
				d.mkdirs();
		   }catch(Exception e) {
			   e.printStackTrace();
		   }
		}

 	   String uploadPath = fullUploadDir.concat(fullUploadDir.endsWith("/")?"":"/").concat(writeFileName);
 	   
 	   try (InputStream is = file.getInputStream(); FileOutputStream fos = new FileOutputStream(uploadPath, false)){
 		   IOUtils.copy(is, fos);
 		   String url = FileUtil.ConcatPath(resoConfig.getDiskDownloadUrl(), relPath);
// 	   		if(logInfo) {
//	 	   		FileInfo fi = new FileInfo(bizId, bizFlag);
//	 			fi.setRelPath(relPath);
//	 			fi.setId(IdGenerator.Id32());
//	 			fi.setName(originalName);
//
//	 			LgnUserVo luv = CurrLgnUserVo.Get();
//	 			if(null != luv) {
//	 	 			fi.setUploaderId(luv.getUserId());
//	 	 			fi.setUploaderName(luv.getDisplayName());
//	 			}
//	 			fi.setSize(file.getSize());
//	 			fi.setType(ext);
//
//	 			baseDao.addObj(fi);
// 	   		}
 	   
 			UploadVo uv = new UploadVo(relPath, originalName, url);
 			uv.setBizId(bizId);
 			uv.setBizFlag(bizFlag);
 			
 		   return DataVo.Success(uv);
 	   } catch (IOException e) {
			e.printStackTrace();
 	   }

	   return DataVo.Fail("Uploading file failed.");
	}
	
	/** Obtain the absolute path of the file according to the relative path of the file */
	public String absolutePath(String relativePath, String bizFlag){
		if(null==relativePath) {
			relativePath = "";
		}
		return FileUtil.ConcatPath(resoConfig.getDiskUpload(), relativePath);
	}

	/** Obtain the complete address of file download according to the relative path where the file is located */
	public String downloadUrl(String relativePath, String bizFlag){
		if(null==relativePath) {
			relativePath = "";
		}
		return FileUtil.ConcatPath(resoConfig.getDiskDownloadUrl(), relativePath);
	}
	
}
